package com.freeheart.validation.constraintvalidators.in;


import org.springframework.core.annotation.AnnotationAwareOrderComparator;

import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

/**
 * 用于组合所有能够提供InCollection实例的处理器。
 * 如果需要提供自定义的 InCollection实例提供处理器，可利用SPI机制，
 * 在`META-INF/service/com.freeheart.validation.constraintvalidators.in.InCollectionSupplier`定义你自己的InCollectionInstance，
 * 注意，需要考虑实例的顺序，实现{@code Ordered} 或者 标记 {@code Order}注解都是可以
 *
 * @author: EmperorHeart
 * @date: 2025/5/9 23:45
 * @description
 */
public class CompositionInConstraintValidator extends AbstractInConstraintValidator {
    /**
     * 提供InCollection实例的InCollectionInstance 集合
     */
    private final List<InCollectionSupplier> inCollectionInstancesList;

    public CompositionInConstraintValidator() {
        super();
        this.inCollectionInstancesList = loadInCollectionInstanceList();
    }

    /**
     * 从`META-INF/service/com.freeheart.validation.constraintvalidators.in.InCollectionSupplier`中加载出所有的实现类
     *
     * @return List<InCollectionSupplier>
     */
    private List<InCollectionSupplier> loadInCollectionInstanceList() {
        ServiceLoader<InCollectionSupplier> load = ServiceLoader.load(InCollectionSupplier.class);
        List<InCollectionSupplier> inC = new ArrayList<>();
        load.forEach(inC::add);
        // 排序：实现了Ordered接口或者@Order注解
        AnnotationAwareOrderComparator.sort(inC);
        return inC;
    }

    /**
     * 获取InCollection实例
     *
     * @param clazz Class<? extends InCollection>
     * @return InCollection实例
     */
    @Override
    protected InCollection getInCollection(Class<? extends InCollection> clazz) {
        for (InCollectionSupplier instance : inCollectionInstancesList) {
            if (instance.support()) {
                return instance.getInCollectionInstance(clazz);
            }
        }
        throw new NoSuchInCollectionSupplierException("没有一个符合条件的 InCollectionSupplier 可以根据 " + clazz + "生成实例");
    }
}
